package org.datastealer.dao.mysql;

import org.datastealer.bean.CustomSqlResult;
import org.datastealer.dao.api.CustomDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.sql.Statement;


/**
 * Note：
 *
 * @author ：mengjw
 * @description：mysql用户自定义sqlDAO实现
 * @date ：Created in 2020/9/21
 */
@Component("customDao")
public class MysqlCustomDao implements CustomDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Object runCustomSql(String sql) {
        return jdbcTemplate.execute(new StatementCallback<Object>() {
            @Override
            public Object doInStatement(Statement statement) throws SQLException, DataAccessException {
                long startTime = System.currentTimeMillis();
                statement.execute(sql);
                int count = statement.getUpdateCount();
                if (count == -1) {
                    return CustomSqlResult.getDataResult(convertListMap(statement.getResultSet()), System.currentTimeMillis() - startTime);
                } else if (count == 0) {
                    return CustomSqlResult.getBooleanResult(System.currentTimeMillis() - startTime);
                } else {
                    return CustomSqlResult.getAffectResult(count, System.currentTimeMillis() - startTime);
                }
            }
        });
    }

}